import { ConfigProvider, Popconfirm } from 'antd'
import zhCN from 'antd/locale/zh_CN'
import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn'
import { useCallback, useEffect, useMemo, useState } from 'react'
import Login from './components/Login'
import QuestionResult from './components/QuestionResult'
import ShuDu from './components/ShuDu'
import { DataContext, DataContextParams } from './logic/DataContext'
import { LOGIN_USER, QUESTION_LIST, getLSData } from './logic/handleLS'
import { isValidArray } from './logic/utils'
import { request } from './logic/request'

import './App.scss'

dayjs.locale('zh-cn')

// 保存在 ls 中的信息，如果有，说明已经登录
const lsUsername = getLSData(LOGIN_USER)

function App() {
  // 设置选中的高亮 number
  const [highLightNumber, setHighLightNumber] = useState(0)
  // 是否展示登录
  const [isLogin, setIsLogin] = useState(!lsUsername)
  const [username, setUsername] = useState(lsUsername)
  /** 完成的题目信息 */
  const [finishedQuestions, setFinishedQuestions] = useState<
    ShuDuNS.ResultItemStr[]
  >([])
  // 重置组件
  const [resetIndex, setResetIndex] = useState(0)

  function exitLogin() {
    setUsername('')
    setIsLogin(true)
    setHighLightNumber(0)
    setFinishedQuestions([])
    localStorage.clear()
    setResetIndex((old) => old + 1)
    request({
      url: '/exitUser',
      method: 'post',
      data: {
        username
      }
    })
  }

  // 数据的 context 数据
  const dataContextData = useMemo<DataContextParams>(
    () => ({
      highLightNumber,
      setHighLightNumber,
      username,
      finishedQuestions
    }),
    [finishedQuestions, highLightNumber, username]
  )

  // 完成题目操作
  const handleFinishQuestion = useCallback(
    (question: ShuDuNS.ResultItemStr) => {
      setFinishedQuestions((old) => {
        // 先校验下对应 id 的题目是否已经存在，如果已经存在，则不进行添加操作
        if (old.findIndex((item) => item.id === question.id) > -1) {
          return old
        }
        return [question, ...old]
      })
    },
    []
  )

  // 在刚加载页面的时候，去 ls 取所有的数据，如果有已经完成的，则直接设置到已完成的题目中去
  useEffect(() => {
    const questionRecord: ShuDuNS.QuestionItem[] = getLSData(QUESTION_LIST)
    if (isValidArray(questionRecord)) {
      const finishedQuestion: ShuDuNS.ResultItemStr[] = []
      questionRecord.forEach((item) => {
        if (item.isFinished) {
          finishedQuestion.unshift({
            id: item.id,
            level: item.level,
            duration: item.duration ?? 0
          })
        }
      })
      setFinishedQuestions(finishedQuestion)
    }
  }, [])

  return (
    <ConfigProvider locale={zhCN}>
      <div className="App" key={resetIndex}>
        {isLogin ? (
          <Login
            onSuccess={(name) => {
              setUsername(name)
              setIsLogin(false)
            }}
          />
        ) : (
          <DataContext.Provider value={dataContextData}>
            <header className="App-header">
              <Popconfirm title="确定要退出当前用户吗？" onConfirm={exitLogin}>
                <div className="header--right">
                  你的名字：{username.replace('www', '')}
                </div>
              </Popconfirm>
            </header>
            <main className="main">
              <ShuDu onFinish={handleFinishQuestion} />
              <div className="main--right">
                <QuestionResult finishedQuestions={finishedQuestions} />
              </div>
            </main>
          </DataContext.Provider>
        )}
      </div>
    </ConfigProvider>
  )
}

export default App
